//
//  MTNewsListModel.m
//  MobTimes
//
//  Created by 江山 王 on 4/30/12.
//  Copyright (c) 2012 Finalist. All rights reserved.
//

#import "MTStartupsModel.h"
#import "MTURLRequest.h"
#import "GDataXMLNode.h"
#import "MTStartupsPO.h"
#import "MTStartupsViewController.h"

@implementation MTStartupsModel

@synthesize newsList;
@synthesize pageNumber;

#pragma mark - Public methods implementation

- (id)init {
    if (self = [super init]) {
        self.isLoading = NO;
        NSMutableArray *_tempArray = [[NSMutableArray alloc] init];
        self.newsList = _tempArray;
        pageNumber = 1;
        [_tempArray release];
        _tempArray = nil;
    }
    return self;
}

- (void)setIsLoading:(BOOL)isLoading {
    _isLoading = isLoading;
    if (_isLoading) {
        [(MTStartupsViewController *)_controller setDraggingRefreshStatus:MTTableHeaderDragRefreshLoading];
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:kDefaultFastTransitionDuration];
        
        if (((MTStartupsViewController *)_controller).tableView.contentOffset.y <= 0) {
            ((MTStartupsViewController *)_controller).tableView.contentInset = UIEdgeInsetsMake(MTDragRefreshViewHeight, 0.0f, 0.0f, 0.0f);
        }
        [UIView commitAnimations];
        ((MTStartupsViewController *)_controller).tableView.contentInset = UIEdgeInsetsMake(MTDragRefreshViewHeight, 0.0f, 0.0f, 0.0f);
    } else {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:kDefaultTransitionDuration];
        ((MTStartupsViewController *)_controller).tableView.contentInset = UIEdgeInsetsZero;
        [UIView commitAnimations];
        [(MTStartupsViewController *)_controller setDraggingRefreshStatus:MTTableHeaderDragRefreshPullToReload];
        self.isReloading = NO;
    }
}

- (void)loadData { 
    self.isLoading = YES;
    MTURLRequest *_request = [[MTURLRequest alloc] initWithDelegate:self];
    _request.urlString = [NSString stringWithFormat:_urlStr, pageNumber];
    [_request sendAsynchrously];
    [_request release];
    _request = nil;
    return;
}

- (void)reloadData {
    self.isReloading = YES;
    pageNumber = 1;
    [self loadData];
}

#pragma mark - MTURLRequestDelegate

- (void)requestDidCancelLoad:(MTURLRequest *)request {
    self.isLoading = NO;
}

- (void)requestDidStartLoad:(MTURLRequest *)request {
    self.isLoading = YES;
}

- (void)request:(MTURLRequest *)request didFailLoadWithError:(NSError*)error {
    self.isLoading = NO;
}

- (void)requestDidFinishLoad:(MTURLRequest *)request {
    if (self.isReloading) {
        [self.newsList removeAllObjects];
    }
    
    //Parse html data
    GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithHTMLData:request.responseData options:0 error:NULL];
    if (doc) {
        NSError *_error = nil;
        NSMutableArray *_postsNodes = [[doc nodesForXPath:MT_String("//article[@class='posts']") error:&_error] mutableCopy];
        if (_postsNodes && _postsNodes.count > 0) {
            MTDebugLog(MT_String("_postsNodes size is %d"), _postsNodes.count);
            NSMutableArray *_newsListPOes = [[NSMutableArray alloc] init];
            for (GDataXMLElement *_postsNode in _postsNodes) {
                MTDebugLog(MT_String("_postsNode is \n %@"), [_postsNode stringValue]);
                MTStartupsPO *_po = [[MTStartupsPO alloc] init];
                MTDebugLog(MT_String("=========================================================================================="));
                NSString *_postTitle = nil;
                NSString *_postContent = nil;
                NSString *_postImgURL = nil;
                NSString *_postLink = nil;
                NSString *_postAuthor = nil;
                NSString *_postDateTime = nil;
                NSString *_postTimeAgo = nil;
                NSString *_postCommentCount = nil;
                
                //title和link
                NSArray *_h3Nodes = [_postsNode nodesForXPath:MT_String("h3") error:nil];
                if (_h3Nodes && _h3Nodes.count > 0) {
                    _postTitle = [[_h3Nodes objectAtIndex:0] stringValue];
                    NSArray *_aNodes = [[_h3Nodes objectAtIndex:0] nodesForXPath:MT_String("a") error:nil];
                    if (_aNodes && _aNodes.count > 0) {
                        _postLink = [[[_aNodes objectAtIndex:0] attributeForName:MT_String("href")] stringValue];
                    }
                }
                
                //author、datetime、timeago和post comment count
                NSArray *_postMetaNodes = [_postsNode nodesForXPath:MT_String("div[@class='postmeta']") error:nil];
                if (_postMetaNodes && _postMetaNodes.count > 0) {
                    //author
                    NSArray *_authorNodes = [[_postMetaNodes objectAtIndex:0] nodesForXPath:MT_String("span[@class='author']") error:nil];
                    if (_authorNodes && _authorNodes.count > 0) {
                        _postAuthor = [[_authorNodes objectAtIndex:0] stringValue];
                    }
                    //post datetime and post timeago
                    NSArray *_strongTimeAgoNodes = [[_postMetaNodes objectAtIndex:0] nodesForXPath:MT_String("strong") error:nil];
                    if (_strongTimeAgoNodes && _strongTimeAgoNodes.count > 0) {
                        NSString *_postTime = [[_strongTimeAgoNodes objectAtIndex:0] stringValue];
                        _postDateTime = _postTime;
                        _postTimeAgo = _postTime;                        
//                        NSArray *_timeAgoNodes = [[_strongTimeAgoNodes objectAtIndex:0] nodesForXPath:MT_String("abbr[@class='timeago']") error:nil];
//                        if (_timeAgoNodes && _timeAgoNodes.count > 0) {
//                            _postDateTime = [[[_timeAgoNodes objectAtIndex:0] attributeForName:MT_String("title")] stringValue];
//                            _postTimeAgo = [[_timeAgoNodes objectAtIndex:0] stringValue];
//                        }
                    }
                    //post comment count
                    NSArray *_commentCountNodes = [[_postMetaNodes objectAtIndex:0] nodesForXPath:MT_String("span[@class='comment-count-number']") error:nil];
                    if (_commentCountNodes) {
                        _postCommentCount = [[_commentCountNodes objectAtIndex:0] stringValue];
                    }
                }
                                
                //imgurl和abstract
                NSArray *_rowNodes = [_postsNode nodesForXPath:MT_String("div[@class='row']") error:nil];
                if (_rowNodes && _rowNodes.count > 0) {
                    //imgurl
                    NSArray *_threeColumnsNodes = [[_rowNodes objectAtIndex:0] nodesForXPath:MT_String("div[@class='three columns']") error:nil];
                    if (_threeColumnsNodes && _threeColumnsNodes.count > 0) {
                        NSArray *_thumbnailHideOnPhonesNodes = [[_threeColumnsNodes objectAtIndex:0] nodesForXPath:MT_String("div[@class='thumbnail hide-on-phones']") error:nil];
                        if (_thumbnailHideOnPhonesNodes && _thumbnailHideOnPhonesNodes.count > 0) {
                            NSArray *_aNodes = [[_thumbnailHideOnPhonesNodes objectAtIndex:0] nodesForXPath:MT_String("a") error:nil];
                            if (_aNodes && _aNodes.count > 0) {
                                NSArray *_imgNodes = [[_aNodes objectAtIndex:0] nodesForXPath:MT_String("img") error:nil];
                                if (_imgNodes && _imgNodes.count > 0) {
                                    _postImgURL = [[[_imgNodes objectAtIndex:0] attributeForName:MT_String("src")] stringValue];
                                }
                            }
                        }
                    }
                    
                    //abstract
                    NSArray *_nineColumnsNodes = [[_rowNodes objectAtIndex:0] nodesForXPath:MT_String("div[@class='nine columns']") error:nil];
                    if (_nineColumnsNodes && _nineColumnsNodes.count > 0) {
                        _postContent = [[_nineColumnsNodes objectAtIndex:0] stringValue];
                    }
                }
                _po.title = [_postTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.abstract = [_postContent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.imgURLString = [_postImgURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.detailURLString = [_postLink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.author = [_postAuthor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.datetime = [_postDateTime stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.timeAgo = [_postTimeAgo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                _po.commentsCount = [_postCommentCount stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                [_newsListPOes addObject:_po];
                MTDebugLog(MT_String("_postTitle : %@\n _postContent : %@\n _postImgURL : %@\n _postLink : %@\n"), _postTitle, _postContent, _postImgURL, _postLink);
            }
            [self.newsList addObjectsFromArray:_newsListPOes];
        } else {
            MTDebugLog(MT_String("_postsNodes is nil or size is zero."));
        }
    }
    [doc release];
    
    pageNumber ++;
    self.isLoading = NO;
    [super didFinishLoad:request];
}

- (void)dealloc {
    self.newsList = nil;
    [super dealloc];
}

@end